package im.notify.server;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.alibaba.fastjson.JSON;

import manager.DefaultSessionManager;
import manager.MessageManager;

public class IoHandler extends IoHandlerAdapter {

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		System.out.println(session.getRemoteAddress() + " create");
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		System.out.println("open");
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {

		UserInfoAttached uia = (UserInfoAttached) session.getAttribute("userInfo");
		// 发送离线通知
		// 若新的连接已经建立，切上个失效连接还未关闭，则不发送离线消息
		if (uia != null && DefaultSessionManager.share().getSession(uia.getUserAccount()) != session) {
			System.out.println("已经重连了");
		} else if (uia != null && DefaultSessionManager.share().getSession(uia.getUserAccount()) == session) {
			Notify.Online offline = new Notify.Online();
			offline.setAccount(uia.getUserAccount());
			offline.setLinestatus(Notify.Online.OFFLINE);
			String str = JSON.toJSONString(offline);
			MessageManager.broadcast(str);
		}

		// 移除已经断开的连接
		if (uia != null && DefaultSessionManager.share().getSession(uia.getUserAccount()) == session) {
			DefaultSessionManager.share().removeSession(uia.getUserAccount());
		}

		System.out.println(uia.getUserAccount() + ":closed");

	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {

	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		System.out.println(session.getRemoteAddress() + "收到：" + message);
		String strMsg = (String) message;

		if (strMsg.startsWith("{\"a\":\"bind")) {
			UserInfoAttached uinfo = JSON.parseObject(strMsg, UserInfoAttached.class);
			uinfo.setBindTime(System.currentTimeMillis());

			// 检查是否上一个还没关闭
			IoSession ios = DefaultSessionManager.share().getSession(uinfo.getUserAccount());
			if (ios != null) {
//				ios.close(true);
				ios.write(Notify.BEOFFLINE);
			}

			session.setAttribute("userInfo", uinfo);
			DefaultSessionManager.share().updateSession(session);

			// 广播上线消息
			Notify.Online online = new Notify.Online();
			online.setAccount(uinfo.getUserAccount());
			online.setLinestatus(Notify.Online.ONLINE);
			MessageManager.broadcast(JSON.toJSONString(online));
		}

	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		System.out.println(session.getRemoteAddress() + "写到" + message);
	}

}
